import { Request, Response, Router } from 'express';
import { ensureWorkspacesDir, listProjects, readProjectFile, writeProjectFile, projectExists, deleteProject } from '../utils/fileStorage';

/**
 * Project Routes
 * 
 * REST API endpoints for project management.
 */

ensureWorkspacesDir();

/**
 * Gets all projects
 * @param req - Express request
 * @param res - Express response
 */
const getProjects = (req: Request, res: Response) => {
  try {
    const projectIds = listProjects();
    const projects = projectIds.map(id => {
      const projectData = readProjectFile(id, 'project.json');
      return projectData || { id, name: id, description: 'Project data not found' };
    });
    
    res.json({
      success: true,
      data: projects
    });
  } catch (error) {
    console.error('Error getting projects:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to get projects'
    });
  }
};

/**
 * Gets a project by ID
 * @param req - Express request
 * @param res - Express response
 */
const getProjectById = (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    if (!projectExists(id)) {
      res.status(404).json({
        success: false,
        message: 'Project not found'
      });
      return;
    }
    
    const projectData = readProjectFile(id, 'project.json');
    
    if (!projectData) {
      res.status(500).json({
        success: false,
        message: 'Failed to read project data'
      });
      return;
    }
    
    res.json({
      success: true,
      data: projectData
    });
  } catch (error) {
    console.error('Error getting project:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to get project'
    });
  }
};

/**
 * Creates a new project
 * @param req - Express request
 * @param res - Express response
 */
const createProject = (req: Request, res: Response) => {
  try {
    const { id, name, description, resolution, frameRate } = req.body;
    
    // Validate request
    if (!id || !name) {
      res.status(400).json({
        success: false,
        message: 'Project ID and name are required'
      });
      return;
    }
    
    // Check if project already exists
    if (projectExists(id)) {
      res.status(400).json({
        success: false,
        message: 'Project with this ID already exists'
      });
      return;
    }
    
    // Create project data
    const projectData = {
      id,
      name,
      description: description || '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      resolution: resolution || { width: 1920, height: 1080 },
      frameRate: frameRate || 30
    };
    
    // Save project data
    writeProjectFile(id, 'project.json', projectData);
    
    res.status(201).json({
      success: true,
      data: projectData
    });
  } catch (error) {
    console.error('Error creating project:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to create project'
    });
  }
};

/**
 * Updates a project
 * @param req - Express request
 * @param res - Express response
 */
const updateProject = (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const updateData = req.body;
    
    // Check if project exists
    if (!projectExists(id)) {
      res.status(404).json({
        success: false,
        message: 'Project not found'
      });
      return;
    }
    
    // Read existing project data
    const projectData = readProjectFile(id, 'project.json');
    
    if (!projectData) {
      res.status(500).json({
        success: false,
        message: 'Failed to read project data'
      });
      return;
    }
    
    // Update project data
    const updatedProject = {
      ...projectData,
      ...updateData,
      id: projectData.id, // Ensure ID doesn't change
      updatedAt: new Date().toISOString()
    };
    
    // Save updated project data
    writeProjectFile(id, 'project.json', updatedProject);
    
    res.json({
      success: true,
      data: updatedProject
    });
  } catch (error) {
    console.error('Error updating project:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update project'
    });
  }
};

/**
 * Deletes a project
 * @param req - Express request
 * @param res - Express response
 */
const deleteProjectRoute = (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    // Check if project exists
    if (!projectExists(id)) {
      res.status(404).json({
        success: false,
        message: 'Project not found'
      });
      return;
    }
    
    // Delete project directory
    deleteProject(id);
    
    res.json({
      success: true,
      message: 'Project deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting project:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to delete project'
    });
  }
};

// Create router
const router = Router();

// Define routes
router.get('/', getProjects);
router.get('/:id', getProjectById);
router.post('/', createProject);
router.put('/:id', updateProject);
router.delete('/:id', deleteProjectRoute);

export default router;

/**
 * Project Interface
 * 
 * Represents a project in the system.
 */
interface Project {
  id: string;
  name: string;
  description: string;
  createdAt: string;
  updatedAt: string;
  sceneData?: any; // Using 'any' for now, would be SceneData in full implementation
  resolution?: {
    width: number;
    height: number;
  };
  frameRate?: number;
}

/**
 * ProjectFile Interface
 * 
 * Represents a file associated with a project.
 */
interface ProjectFile {
  id: string;
  projectId: string;
  name: string;
  type: string;
  path: string;
  uploadedAt: string;
}